package org.fh.controller.fhoa;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.fh.controller.base.BaseController;
import org.fh.dto.*;
import org.fh.entity.Page;
import org.fh.entity.PageData;
import org.fh.service.fhoa.ClockinmyService;
import org.fh.service.fhoa.CustomerPositionService;
import org.fh.service.fhoa.ICustomerInfoService;
import org.fh.service.fhoa.INewLogDayService;
import org.fh.service.system.FHlogService;
import org.fh.service.system.UsersService;
import org.fh.util.Jurisdiction;
import org.fh.util.ObjectExcelView;
import org.fh.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.regex.Pattern;

@RequestMapping("/newlogday")
@RestController
public class NewLogDayController extends BaseController {

    private static final String IMAGE_URL_REGEX = "^(https?|ftp)://.*\\.(jpg|jpeg|png|gif|bmp)$";
    private static final Pattern IMAGE_URL_PATTERN = Pattern.compile(IMAGE_URL_REGEX, Pattern.CASE_INSENSITIVE);


    @Autowired
    private INewLogDayService iNewLogDayService;

    @Autowired
    private ICustomerInfoService iCustomerInfoService;

    @Autowired
    private CustomerPositionService customerPositionService;

    @Autowired
    private UsersService usersService;


    @Autowired
    private ClockinmyService clockinmyService;

    @Autowired
    private FHlogService FHLOG;

    /**
     * 保存
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    @RequiresPermissions("newlogday:add")
    @ResponseBody
    public Object add(
            @RequestParam(value = "CUSTOMER_NAME", required = false) String CUSTOMER_NAME,
            @RequestParam(value = "TEL", required = false) String TEL,
            @RequestParam(value = "COMPANY", required = false) String COMPANY,
            @RequestParam(value = "CUSTOMERCHANNELNAME", required = false) String CUSTOMERCHANNELNAME,
            @RequestParam(value = "POSITION", required = false) String POSITION,
            @RequestParam(value = "CUSTOMERLEVEL", required = false) String CUSTOMERLEVEL,
            @RequestParam(value = "STAGE", required = false) String STAGE,
            @RequestParam(value = "CUREECONTENT", required = false) String CUREECONTENT,
            @RequestParam(value = "ISCHANCE", required = false) String ISCHANCE,
            @RequestParam(value = "NEXTCUSTOMERINFO", required = false) String NEXTCUSTOMERINFO,
            @RequestParam(value = "NEXTCONTENT", required = false) String NEXTCONTENT,
            @RequestParam(value = "CTIME", required = false) String CTIME,
            @RequestParam(value = "BZ", required = false) String BZ,
            @RequestParam(value = "COMMUNICATION_RECORD", required = false) String COMMUNICATION_RECORD
    ) throws Exception {

        PageData pd = new PageData();

        //写入表
        String UNAME = Jurisdiction.getName();
        String USERNAME = Jurisdiction.getUsername();
        pd.put("WORKLOG_ID", this.get32UUID());
        pd.put("UNAME", UNAME);
        pd.put("CUSTOMER_NAME", CUSTOMER_NAME);
        pd.put("TEL", TEL);
        pd.put("COMPANY", COMPANY);
        pd.put("CUSTOMERCHANNELNAME", CUSTOMERCHANNELNAME);
        pd.put("POSITION", POSITION);
        pd.put("CUSTOMERLEVEL", CUSTOMERLEVEL);
        pd.put("STAGE", STAGE);
        pd.put("COMMUNICATION_RECORD", COMMUNICATION_RECORD);
        pd.put("CUREECONTENT", CUREECONTENT);
        pd.put("ISCHANCE", ISCHANCE);
        pd.put("NEXTCUSTOMERINFO", NEXTCUSTOMERINFO);
        pd.put("NEXTCONTENT", NEXTCONTENT);
        pd.put("USERNAME", USERNAME);    //
        pd.put("CTIME", CTIME);     //填写时间
        pd.put("ITIME", new Date());    //创建日期
        String DEPARTMENT_ID = Jurisdiction.getDEPARTMENT_IDS();
        pd.put("DEPARTMENT_ID", DEPARTMENT_ID);
        pd.put("BZ", BZ);
        iNewLogDayService.save(pd);

        PageData customerPd = new PageData();
        //写入表
        customerPd.put("CUSTOMER_ID", this.get32UUID());
        customerPd.put("CUSTOMER_NAME", CUSTOMER_NAME);
        customerPd.put("POSITION", POSITION);
        customerPd.put("COMPANY", COMPANY);
        customerPd.put("CUSTOMERCHANNELNAME", CUSTOMERCHANNELNAME);
        customerPd.put("CUSTOMERLEVEL", CUSTOMERLEVEL);
        customerPd.put("TEL", TEL);
        customerPd.put("ISCHANCE", ISCHANCE);
        customerPd.put("STAGE", STAGE);
        customerPd.put("USERNAME", USERNAME);    //

        PageData user = new PageData();
        user.put("USERNAME", Jurisdiction.getUsername());
        PageData Username = usersService.findByUsername(user);
        if (!Username.isEmpty()) {
            String USER_ID = Username.getString("USER_ID"); // 假设getString自动处理null
            customerPd.put("USER_ID", USER_ID);
        }

        customerPd.put("CREATE_TIME", new Date());    //创建时间
        customerPd.put("UPDATE_TIME", new Date());    //创建时间
        List<ClockinmyDTO> PHOTOADDA = clockinmyService.getPhotoAddaByUnameAndCustomerName(UNAME, CUSTOMER_NAME);

        if (PHOTOADDA.isEmpty()) {
            customerPd.put("PHOTOADDA", null);
        } else {
            String photoAddaStr = PHOTOADDA.toString();
            // 去除首尾的方括号
            photoAddaStr = photoAddaStr.substring(1, photoAddaStr.length() - 1);
            customerPd.put("PHOTOADDA", photoAddaStr);
        }
        customerPd.put("REMARK", BZ);
        iCustomerInfoService.save(customerPd);

        /**
         * 职业
         */
        PageData optionPd = new PageData();
        if (customerPositionService.isPositionNameExists(POSITION)) {
            Map<String, Object> map = new HashMap<>();
            String errInfo = "POSITION_NAME already exists";
            map.put("result", errInfo);
            return map;
        }

        optionPd.put("POSITION_NAME", POSITION);
        optionPd.put("POSITION_ID", this.get32UUID());
        optionPd.put("USERNAME", Jurisdiction.getUsername());
        optionPd.put("CREATE_TIME", new Date());
        customerPositionService.save(optionPd);
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        map.put("result", errInfo);
        return map;
    }

    /**
     * 删除
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @RequiresPermissions("newlogday:del")
    @ResponseBody
    public Object delete() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        iNewLogDayService.delete(pd);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 修改
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    @RequiresPermissions("newlogday:edit")
    @ResponseBody
    public Object edit() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        iNewLogDayService.edit(pd);
        // 从 newlogday 的 PageData 中获取相关信息，用于修改 customer
        String CUSTOMER_NAME = (String) pd.get("CUSTOMER_NAME");
        String POSITION = (String) pd.get("POSITION");
        String COMPANY = (String) pd.get("COMPANY");
        String CUSTOMERCHANNELNAME = (String) pd.get("CUSTOMERCHANNELNAME");
        String CUSTOMERLEVEL = (String) pd.get("CUSTOMERLEVEL");
        String TEL = (String) pd.get("TEL");
        String ISCHANCE = (String) pd.get("ISCHANCE");
        String STAGE = (String) pd.get("STAGE");
        String UPDATE_TIME = (String) pd.get("CTIME");
        String COMMUNICATION_RECORD = (String) pd.get("COMMUNICATION_RECORD");

        String BZ = (String) pd.get("BZ");

        String USERNAME = (String) pd.get("Jurisdiction.getUsername()");
        String REMARK = (String) pd.get("BZ");
        // 写入 oa_customer_info 表
        PageData customerPd = new PageData();
        customerPd.put("CUSTOMER_NAME", CUSTOMER_NAME);
        customerPd.put("POSITION", POSITION);
        customerPd.put("COMPANY", COMPANY);
        customerPd.put("CUSTOMERCHANNELNAME", CUSTOMERCHANNELNAME);
        customerPd.put("CUSTOMERLEVEL", CUSTOMERLEVEL);
        customerPd.put("TEL", TEL);
        customerPd.put("ISCHANCE", ISCHANCE);
        customerPd.put("STAGE", STAGE);
        customerPd.put("REMARK", BZ);
        customerPd.put("UPDATE_TIME", UPDATE_TIME);
        customerPd.put("USERNAME", USERNAME);
        customerPd.put("CUSTOMER_ID", this.get32UUID());

        CustomerInfoDTO customerInfoDTO = iCustomerInfoService.selectByUname(USERNAME, CUSTOMER_NAME);
        Long customerId = customerInfoDTO.getCustomerId();
        pd.put("CUSTOMER_ID", customerId);
        iCustomerInfoService.edit(pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    @RequiresPermissions("newlogday:list")
    @ResponseBody
    public Object list(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String isMy = pd.getString("isMy");
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        String lastStart = pd.getString("lastStart");                    //开始时间
        String lastEnd = pd.getString("lastEnd");                        //结束时间
        if (Tools.notEmpty(lastStart)) pd.put("lastStart", lastStart + " 00:00:00");
        if (Tools.notEmpty(lastEnd)) pd.put("lastEnd", lastEnd + " 00:00:00");
        String USERNAME = Jurisdiction.getUsername();                    //用户名
        String department_ids = Jurisdiction.getDEPARTMENT_IDS();

        if (Tools.isEmpty(department_ids)) {
            department_ids = ""; // 初始化空字符串，避免后续 NPE
        }
        if ("false".equals(isMy)) {
            if ("".equals(department_ids) || "无权".equals(department_ids)) {
                pd.put("item", "");                                            //根据部门ID过滤
                if (!"admin".equals(USERNAME)) pd.put("USERNAME", USERNAME);    //非admin用户时
            } else {
                pd.put("ORUSERNAME", USERNAME);
                pd.put("item", department_ids.replaceFirst("\\(", "\\('" + Jurisdiction.getDEPARTMENT_ID() + "',"));
            }
        } else {
            pd.put("USERNAME", USERNAME);
        }
        page.setPd(pd);
        List<PageData> varList = iNewLogDayService.list(page);            //列出Worklog列表
        map.put("varList", varList);
        map.put("page", page);
        map.put("USERNAME", USERNAME);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改页面获取数据
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/goEdit")
    @RequiresPermissions("newlogday:edit")
    @ResponseBody
    public Object goEdit(@RequestParam(value = "WORKLOG_ID", required = false) String WORKLOG_ID) throws Exception {

        if (WORKLOG_ID == null) {
            System.out.println("WORKLOG_ID 为 null，请检查前端传递的参数");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("WORKLOG_ID", WORKLOG_ID);
        pd = iNewLogDayService.findById(pd);    //根据ID读取
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 导出到excel
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/excel")
    @RequiresPermissions("toExcel")
    public ModelAndView exportExcel() throws Exception {
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("姓名");    //1
        titles.add("联系方式");    //2
        titles.add("公司/单位");    //3
        titles.add("客户类型(j甲方/渠道)");    //4
        titles.add("客户岗位");    //5
        titles.add("客户等级");    //6
        titles.add("跟进阶段");    //7
        titles.add("当日工作内容");    //8
        titles.add("本日发现商机");    //9
        titles.add("填写时间");    //10
        titles.add("备注");    //11
        titles.add("创建日期");    //12
        titles.add("用户名");    //13
        titles.add("沟通记录");    //14


        titles.add("部门ID");    //15
        dataMap.put("titles", titles);

        String lastStart = pd.getString("lastStart");                    //开始时间
        String lastEnd = pd.getString("lastEnd");                        //结束时间
        if (Tools.notEmpty(lastStart)) pd.put("lastStart", lastStart + " 00:00:00");
        if (Tools.notEmpty(lastEnd)) pd.put("lastEnd", lastEnd + " 00:00:00");

        List<PageData> varOList = iNewLogDayService.listAll(pd);
        List<PageData> varList = new ArrayList<PageData>();
        for (int i = 0; i < varOList.size(); i++) {
            PageData vpd = new PageData();
            vpd.put("var1", varOList.get(i).getString("UNAME"));        //1
            vpd.put("var2", varOList.get(i).getString("TEL"));        //2
            vpd.put("var3", varOList.get(i).getString("COMPANY"));        //3
            vpd.put("var4", varOList.get(i).getString("CUSTOMERCHANNELNAME"));        //4
            vpd.put("var5", varOList.get(i).getString("POSITION"));        //5
            vpd.put("var6", varOList.get(i).getString("CUSTOMERLEVEL"));        //6
            vpd.put("var7", varOList.get(i).getString("STAGE"));        //7
            vpd.put("var8", varOList.get(i).getString("CUREECONTENT"));        //8
            vpd.put("var9", varOList.get(i).getString("ISCHANCE"));        //9
            vpd.put("var10", varOList.get(i).getString("CTIME"));        //10
            vpd.put("var11", varOList.get(i).getString("BZ"));        //11
            vpd.put("var12", varOList.get(i).getString("ITIME"));        //12
            vpd.put("var13", varOList.get(i).getString("UNAME"));        //13
            vpd.put("var14", varOList.get(i).getString("COMMUNICATION_RECORD"));        //14
            vpd.put("var15", varOList.get(i).getString("DEPARTMENT_ID"));        //14


            varList.add(vpd);
        }
        dataMap.put("varList", varList);
        ObjectExcelView erv = new ObjectExcelView();
        mv = new ModelAndView(erv, dataMap);
        return mv;
    }


    /**
     * 查询姓名、总客户量和月客户量
     *
     * @return 包含统计结果的 Map 对象
     * @throws Exception 异常
     */
//    @RequiresPermissions("newLogDay:findCustomerStats")
    @RequestMapping(value = "/findCustomerStats")
    @ResponseBody
    public Object findCustomerStats() throws Exception {
        Map<String, Object> map = new HashMap<>();
        String errInfo = "success";
        PageData pd = new PageData();

        String USERNAME = Jurisdiction.getUsername();                    //用户名
        pd.put("USERNAME", USERNAME);
        List<PageData> resultList = iNewLogDayService.findCustomerStats(pd);
        map.put("resultList", resultList);
        map.put("result", errInfo);
        return map;
    }


    /**
     * 根据客户姓名查询拜访记录
     *
     * @return 包含查询结果和状态信息的 Map
     * @throws Exception 异常
     */
//        @RequiresPermissions("newLogDay:visitRecords")
    @RequestMapping(value = "/findCustomerVisitRecords")
    @ResponseBody
    public Object findCustomerVisitRecords(@RequestParam(value = "CUSTOMER_NAME", required = false) String CUSTOMER_NAME) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd.put("CUSTOMER_NAME", CUSTOMER_NAME);
        // 假设客户姓名通过 pd 中的某个键传递，这里假设键为 "customerName"
        List<CustomerVisitDTO> customerVisitRecords = iNewLogDayService.findCustomerVisitRecords(pd);
        map.put("resultList", customerVisitRecords);
        map.put("result", errInfo);
        return map;
    }


    /**
     * 查询客户姓名列表
     *
     * @return
     */
//    @GetMapping("/customerNames")
    @RequestMapping(value = "/customerNames")
    @ResponseBody
    public Object selectCustomerName() {
        Map<String, Object> map = new HashMap<>();
        String errInfo = "success";
        List<NewLogDayDTO> newLogDayDTOS = iNewLogDayService.selectCustomerName();
        map.put("resultList", newLogDayDTOS);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 查询公司列表
     *
     * @return
     */
//    @GetMapping("/company")
    @RequestMapping(value = "/company")
    @ResponseBody
    public Object selectCompany() {
        Map<String, Object> map = new HashMap<>();
        String errInfo = "success";
        List<CustomerCompanyDTO> customerCompanyDTOS = iNewLogDayService.selectCompany();
        map.put("resultList", customerCompanyDTOS);
        map.put("result", errInfo);
        return map;
    }


    /**
     * 查询公司列表
     *
     * @return
     */
//    @GetMapping("/newLogDetail")
    @RequestMapping(value = "/newLogDetail")
    @ResponseBody
    public Object selectNewLogDetail() {
        Map<String, Object> map = new HashMap<>();
        String errInfo = "success";
        String USERNAME = Jurisdiction.getUsername();                    //用户名
        List<NewLogDetailDTO> newLogDetailDTOS = iNewLogDayService.selectNewLogDetail(USERNAME);
        map.put("resultList", newLogDetailDTOS);
        map.put("result", errInfo);
        return map;
    }

    private boolean isImageUrl(String url) {
        return url != null && IMAGE_URL_PATTERN.matcher(url).matches();
    }
}
